﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Text.RegularExpressions;
using System.ComponentModel;

namespace Nizm0.QOT.Library.Objects
{

    [Serializable]
    [XmlRoot("ProcedureFromFile")]
    public class ProcedureFromFile : Procedure
    {

        private string _location;
        [XmlAttribute("Location")]
        public override string Location
        {
            get { return _location; }
            set { _location = value; }
        }

        [XmlAttribute("Owner")]
        public string Owner { get; set; }

        public ProcedureFromFile() { }

        public ProcedureFromFile(string procName, string file) :
            base(procName)
        {
            Location = file;
            base.SourceType = Procedure.EnumSource.File;
            ReadFile(file);
        }

        void bt1_Click(object sender, EventArgs e)
        {
            ReadFile();
        }

        public override T Deserialize<T>(string xmlobject)
        {
            byte[] byteArray = Encoding.Unicode.GetBytes(xmlobject);
            T ip;
            using (MemoryStream stream = new MemoryStream(byteArray))
            {
                System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(T));
                ip = (T)x.Deserialize(stream);
            }
            return ip;
        }

        public override void Marge(Procedure procedure)
        {
            this.Location = ((ProcedureFromFile)procedure).Location;
            this.Owner = ((ProcedureFromFile)procedure).Owner;

            base.Marge(procedure);
        }

        public bool ReadFile()
        {
            return ReadFile(this.Location);
        }

        public bool ReadFile(string filelocation)
        {
            try
            {
                if (!LoadedFromSettings)
                {
                    lock (this)
                    {
                        if (!LoadedFromSettings)
                        {
                            using (StreamReader strfile = new StreamReader(filelocation, Encoding.Default, true))
                            {
                                //Encoding t = strfile.CurrentEncoding;
                                base.Text = strfile.ReadToEnd();
                                //System.Security.Cryptography.MD5 testMD5 = System.Security.Cryptography.MD5.Create();
                                //System.BitConverter.ToString(testMD5.ComputeHash(new FileStream(filelocation, FileMode.Open)));
                                this._hash = Objects.Procedure.GetMD5Hash(filelocation);
                            }
                            FileInfo infofile = new FileInfo(filelocation);

                            base.CreationTime = infofile.CreationTime;
                            base.ModifiedTime = infofile.LastWriteTime;

                            GetInfoOfProcedure();

                            GetParameters();
                        }
                    }
                    return true;
                }
                else
                    return false;
            }
            catch (UnauthorizedAccessException ex)
            {
                //if (ErrorEvent != null) ErrorEvent(this, ex);
                return false;
            }
            catch (FileLoadException ex)
            {
                //if (ErrorEvent != null) ErrorEvent(this, ex);
                return false;
            }
            catch (FileNotFoundException ex)
            {
                //if (ErrorEvent != null) ErrorEvent(this, ex);
                return false;
            }
            catch (IOException ex)
            {
                //if (ErrorEvent != null) ErrorEvent(this, ex);
                return false;
            }
            catch (Exception ex)
            {
                //if (ErrorEvent != null) ErrorEvent(this, ex);
                return false;
            }
            finally
            {
                //file.Close();
            }
        }

        public override string Serialize()
        {
            TextWriter w = new StringWriter();
            //System.Runtime.Serialization.Formatters.Binary.BinaryFormatter t = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(
            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(ProcedureFromFile));
            x.Serialize(w, this, null);
            w.Flush();
            string text = w.ToString();
            return text;
        }

        public override System.Windows.Forms.UserControl Show()
        {
            System.Windows.Forms.Label tmplabel = new System.Windows.Forms.Label();
            tmplabel.Text = "File " + this.Location;
            tmplabel.AutoSize = true;

            System.Windows.Forms.Button bt1 = new System.Windows.Forms.Button();
            bt1.Text = "Get";
            bt1.Click += new EventHandler(bt1_Click);

            System.Windows.Forms.Control[] tmpcontrolstab = { tmplabel, bt1 };

            return base.Show(tmpcontrolstab);
        }

        public override System.Windows.Forms.UserControl Show(IProcedure proc)
        {
            return base.Show(proc);
        }

        public override void ShowText()
        {
            string[] filetab = { _location };
            Settings.Instance.ProjectSettings.OnOpenProcedure(this, new OpenFormEventArgs(filetab));
        }

        public override string ToString()
        {
            return string.Format("{0}-{1} {2}", this.Name, this.Version, this.CreationTime.ToShortDateString());
        }

        public override System.Xml.Schema.XmlSchema GetSchema()
        {
            return base.GetSchema();
        }

        public override void ReadXml(System.Xml.XmlReader reader)
        {
            reader.MoveToContent();
            this._location = reader.GetAttribute("Location");
            base.ReadXml(reader);
        }

        public override void WriteXml(System.Xml.XmlWriter writer)
        {
            writer.WriteAttributeString("Location", this._location);
            base.WriteXml(writer);
        }
    }
}
